package com.usian.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.usian.entity.Result;
import com.usian.pojo.RedisDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String key = "writer";


    @RequestMapping("findRedis")
    public List<RedisDto> findRedis() {
         Set<ZSetOperations.TypedTuple<String>> set = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, -1);
        List<RedisDto> dtos = JSONArray.parseArray(JSONObject.toJSONString(set), RedisDto.class);
        /*redisTemplate.opsForZSet().incrementScore(key,"张三",10);
        redisTemplate.opsForZSet().incrementScore(key,"李四",11);
        redisTemplate.opsForZSet().incrementScore(key,"王五",12);
        redisTemplate.opsForZSet().incrementScore(key,"赵六",13);*/
        /*ArrayList<RedisDto> list = new ArrayList<>();*/
        return dtos;
    }

    @GetMapping("getRedis")
    public String getRedis(){
         Set<ZSetOperations.TypedTuple<String>> set = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, -1);
         JSONArray array = JSONArray.parseArray(JSONObject.toJSONString(set));
        for (Object o : array) {
            JSONObject object = JSONObject.parseObject(o.toString());
            System.out.println("作家:"+object.getString("value")+"获得点赞数"+object.getLongValue("score"));
        }
        return "okk";
    }

    @GetMapping("setRedis")
    public Result setRedis(String value){
        redisTemplate.opsForZSet().incrementScore(key,value,1);
        return new Result(true,"成功");
    }
}
